﻿using System;
using System.Collections.Generic;
using System.Text;
using ZhCun.Framework.DataAccess.BLL;
using ZhCun.Framework.DataAccess;
using ZhCun.Framework.Common;
using ZhCun.Framework.Common.Models;
using ZhCun.Framework.DataAccess.DataDelegate;
using AccountManager.Runtime;
using AccountManager.TableModel.Model;

namespace AccountManager.AL
{
    public class ALBase
    {
        public ALBase()
        {
            DA = new DACommon();
            _CommonSearchObj = DA.CreateSearch();
        }

        public DACommon DA;
        ISearch _CommonSearchObj;
        public ISearch CommonSearch
        {
            get
            {
                return _CommonSearchObj;
            }
        }
        public string GetGuid()
        {
            return Guid.NewGuid().ToString();
        }
        public DateTime GetNowTime()
        {
            return DateTime.Now;
        }
        public ISearch CreateSearch()
        {
            return DA.CreateSearch();
        }
    }

    public class DACommon : BLLBase
    {
        static DatabaseTypeEnum DBType = ConvertData.StringToEnum<DatabaseTypeEnum>(Configurations.GetAppSettings("DatabaseType"));
        static string ConnStr = Configurations.GetConnectString("Main");
        public DACommon()
            : base(DBType, ConnStr)
        {
            if (_SearchOperatorIdList == null)
            {
                _SearchOperatorIdList = new List<Type>();
                _SearchOperatorIdList.Add(typeof(VConsume));
                _SearchOperatorIdList.Add(typeof(TConsumeType));
                _SearchOperatorIdList.Add(typeof(TConsume));
                _SearchOperatorIdList.Add(typeof(TAccount));
                _SearchOperatorIdList.Add(typeof(VConsumeType));
            }
        }
        /// <summary>
        /// 搜索操作原id的实体列表
        /// </summary>
        static List<Type> _SearchOperatorIdList;

        public override void SearchHandle<TModel>(ref ISearch wh)
        {
            if (wh == null) return;
            Type modelType = typeof(TModel);
            if (_SearchOperatorIdList.Exists(s => s == modelType))
            {
                wh.AddGroup()
                  .And().BracketLeft("OperatorId").Equal(LoginInfo.OperatorId);                
                if (modelType == typeof(VConsumeType) || modelType == typeof(TConsumeType))
                {
                    
                    wh.Or(TConsumeType.CNIsPublic).Equal(true);
                    if (LoginInfo.IsManager)
                    {
                        //管理员允许看所有的账目类型
                        wh.Or(TConsumeType.CNIsPublic).Equal(false);
                    }
                }
                wh.BracketRight();
            }
            base.SearchHandle<TModel>(ref wh);
        }
    }
}